import * as Blockly from 'blockly';
import { javascriptGenerator } from 'blockly/javascript';
import { registerBlocks, registerImportVariableBlocks } from '../blocks';
import { registerGenerators } from '../generators';
import { toolbox } from '../toolbox';
import * as zhHans from 'blockly/msg/zh-hans'

// import { mediaManager } from './media-manager.ts';

// Track initialization state
let blocksRegistered = false;
let generatorsRegistered = false;

// 初始化Blockly
export function initBlockly(
  blocklyDiv: HTMLElement,
  importVariableCallback?: () => string | null | Promise<string | null>
): Blockly.WorkspaceSvg {
  // 注册所有块和生成器 - only register once
  if (!blocksRegistered) {
    registerBlocks();
    blocksRegistered = true;
    console.log('Blocks registered');
  }
  
  if (!generatorsRegistered) {
    registerGenerators();
    generatorsRegistered = true;
    console.log('Generators registered');
  }

  // 设置自定义媒体路径解析器
  // Blockly.utils.toolbox.PATH_TO_MEDIA = (filename) => mediaManager.getMediaUrl(filename);

  // 设置中文语言包 - 在加载时已经设置
  Blockly.setLocale(zhHans as any);
  
  // 创建工作区
  const workspace = Blockly.inject(blocklyDiv, {
    toolbox,
    media: 'assets/blockly-media/',
    sounds: false,
    grid: {
      spacing: 20,
      length: 3,
      colour: '#ccc',
      snap: true,
    },
    zoom: {
      controls: true,
      wheel: true,
      startScale: 1.0,
      maxScale: 3,
      minScale: 0.3,
      scaleSpeed: 1.2,
    },
    trashcan: true,
  });

  // 添加变量动态列表事件监听器
  // workspace.addChangeListener(Blockly.Events.disableOrphans);

  // 添加工具箱分类回调函数
  // workspace.registerToolboxCategoryCallback('VARIABLE_DYNAMIC', function (workspace) {
  //   let xmlList = Blockly.Variables.flyoutCategoryBlocks(workspace);
  //   return xmlList;
  // });
 
 
  // 注册变量导入功能
  if (importVariableCallback) {
    registerImportVariableBlocks(workspace, importVariableCallback);
  }

  console.log('all blocks:', Blockly.Blocks);
  return workspace;
}

// 生成代码
export function generateCode(workspace: Blockly.WorkspaceSvg): string {
  return javascriptGenerator.workspaceToCode(workspace);
}
